#!/usr/bin/env python3
"""
股票数据查看工具
用于查看已存储的股票数据文件信息
"""

import pandas as pd
import json
import os
from pathlib import Path
from typing import Dict, Any

def get_stock_info(symbol: str, interval: str = '1d') -> Dict[str, Any]:
    """获取股票信息"""
    data_dir = Path('./data/stocks')

    # 检查数据文件
    data_file = data_dir / 'daily' / f'{symbol}_{interval}.csv'
    metadata_file = data_dir / 'metadata' / f'{symbol}_{interval}_meta.json'

    info = {
        'symbol': symbol,
        'interval': interval,
        'data_file_exists': data_file.exists(),
        'metadata_file_exists': metadata_file.exists(),
        'name': symbol,
        'record_count': 0,
        'date_range': None,
        'file_size': 0
    }

    # 获取元数据中的名称
    if metadata_file.exists():
        try:
            with open(metadata_file, 'r', encoding='utf-8') as f:
                metadata = json.load(f)
                info['name'] = metadata.get('name', symbol)
        except Exception:
            pass

    # 获取数据文件信息
    if data_file.exists():
        try:
            # 获取文件大小
            info['file_size'] = data_file.stat().st_size

            # 读取数据
            df = pd.read_csv(data_file, index_col=0, parse_dates=True)
            info['record_count'] = len(df)

            # 获取日期范围
            if not df.empty:
                info['date_range'] = {
                    'start': df.index.min().strftime('%Y-%m-%d'),
                    'end': df.index.max().strftime('%Y-%m-%d')
                }

            # 获取列名
            info['columns'] = list(df.columns)

        except Exception as e:
            info['error'] = str(e)

    return info

def display_stock_info(symbol: str, interval: str = '1d'):
    """显示股票信息"""
    info = get_stock_info(symbol, interval)

    print(f"\n{'='*60}")
    print(f"股票信息: {info['name']} ({info['symbol']})")
    print(f"{'='*60}")
    print(f"数据间隔: {info['interval']}")
    print(f"数据文件: {'OK' if info['data_file_exists'] else 'MISSING'}")
    print(f"记录数量: {info['record_count']}")
    print(f"文件大小: {info['file_size']} 字节")

    if info['date_range']:
        print(f"数据范围: {info['date_range']['start']} 至 {info['date_range']['end']}")

    # 获取最新数据并显示
    if info['data_file_exists']:
        try:
            data_dir = Path('./data/stocks')
            data_file = data_dir / 'daily' / f'{symbol}_{interval}.csv'
            df = pd.read_csv(data_file, index_col=0, parse_dates=True)

            if not df.empty:
                print(f"\n最新数据 (最新5条):")
                print("-" * 60)
                # 显示最近5条数据
                recent_data = df.tail(5)
                print(recent_data.to_string())
        except Exception as e:
            print(f"获取最新数据失败: {e}")

    if 'error' in info:
        print(f"错误: {info['error']}")

def list_all_stocks():
    """列出所有已存储的股票"""
    data_dir = Path('./data/stocks/daily')

    if not data_dir.exists():
        print("数据目录不存在")
        return

    files = list(data_dir.glob('*_1d.csv'))
    if not files:
        print("没有找到股票数据文件")
        return

    print(f"\n已存储的股票数据 ({len(files)} 只):")
    print("-" * 80)
    print(f"{'代码':<10} {'名称':<20} {'记录数':<10} {'最新日期':<12} {'文件大小':<10}")
    print("-" * 80)

    for file_path in sorted(files):
        symbol = file_path.stem.replace('_1d', '')
        info = get_stock_info(symbol)

        # 简化日期显示，只显示最新日期
        if info['date_range']:
            latest_date = info['date_range']['end']
        else:
            latest_date = "无数据"

        # 简化文件大小显示
        file_size = info['file_size']
        if file_size > 1024 * 1024:
            file_size = f"{file_size / (1024 * 1024):.1f}MB"
        elif file_size > 1024:
            file_size = f"{file_size / 1024:.1f}KB"
        else:
            file_size = f"{file_size}B"

        print(f"{symbol:<10} {info['name']:<20} {info['record_count']:<10} {latest_date:<12} {file_size:<10}")

def main():
    """主函数"""
    import argparse

    parser = argparse.ArgumentParser(description='股票数据查看工具')
    parser.add_argument('symbol', nargs='?', help='股票代码（如 000001）')
    parser.add_argument('--interval', default='1d', help='数据间隔（默认 1d）')
    parser.add_argument('--list', action='store_true', help='列出所有股票')

    args = parser.parse_args()

    if args.list:
        list_all_stocks()
    elif args.symbol:
        display_stock_info(args.symbol, args.interval)
    else:
        print("请指定股票代码或使用 --list 列出所有股票")
        print("示例:")
        print("  python view_stock_data.py 000001")
        print("  python view_stock_data.py --list")

if __name__ == "__main__":
    main()